#include "DataBase.h"
#include "securec.h"
#include "wifi_device_config.h"
#include <kv_store.h>
#include <stdio.h>
#include <stdlib.h>

#define WIFI_SSID_KEY "ssid"
#define WIFI_PWD_KEY "pwd"
#define WIFI_SEC_KEY "sec"
#define UART_KEY "usart"

int db_save_wifi_config(const WifiDeviceConfig *config)
{
    int ret = 0;
    char buf[128] = {0};
    snprintf(buf, sizeof(buf), "%d", config->securityType);

    ret |= UtilsSetValue(WIFI_SSID_KEY, config->ssid);
    ret |= UtilsSetValue(WIFI_PWD_KEY, config->preSharedKey);
    ret |= UtilsSetValue(WIFI_SEC_KEY, buf);

    if (ret != 0)
    {
        printf("[DB] ERROR: save wifi failed ret=%d\r\n", ret);
    }
    else
    {
        printf("[DB] save wifi config save success, ssid: %s\r\n", config->ssid);
    }
    return ret;
}

int db_get_wifi_config(WifiDeviceConfig *config)
{
    char buf[128] = {0};
    memset_s(config, sizeof(WifiDeviceConfig), 0, sizeof(WifiDeviceConfig));

    int ret = 0;
    ret = UtilsGetValue(WIFI_SSID_KEY, config->ssid, WIFI_MAX_SSID_LEN);
    if (ret < 0)
        goto err;
    ret = UtilsGetValue(WIFI_PWD_KEY, config->preSharedKey, WIFI_MAX_KEY_LEN);
    if (ret < 0)
        goto err;
    ret = UtilsGetValue(WIFI_SEC_KEY, buf, sizeof(buf));
    if (ret < 0)
        goto err;

    config->securityType = atoi(buf);

    return 0;
err:
    printf("[DB] ERROR: get wifi failed ret=%d\r\n", ret);
    return -1;
}

int db_save_uart_config(const IotUartAttribute *config)
{
    char buf[128] = {0};
    snprintf(buf, sizeof(buf), "%d,%d,%d,%d", config->baudRate, config->dataBits, config->parity, config->stopBits);
    return UtilsSetValue(UART_KEY, buf);
}

int db_get_uart_config(IotUartAttribute *config)
{
    char buf[128] = {0};
    int num = 0;
    int ret = 0;
    if (config == NULL)
    {
        return -1;
    }

    config->rxBlock = IOT_UART_BLOCK_STATE_BLOCK;
    config->txBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK;
    if ((ret = UtilsGetValue(UART_KEY, buf, sizeof(buf))) >= 0)
    {
        num = sscanf(buf, "%d,%d,%d,%d", &config->baudRate, &config->dataBits, &config->parity, &config->stopBits);
        return num == 4 ? 0 : -1;
    }
    else
    {
        config->baudRate = 115200;
        config->dataBits = IOT_UART_DATA_BIT_8;
        config->parity = IOT_UART_PARITY_NONE;
        config->stopBits = IOT_UART_STOP_BIT_1;
        return db_save_uart_config(config);
    }
}
